package com.itheima.servcie;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.CodeBean;
import com.itheima.dbservice.BlackListServiceApi;
import com.itheima.dbservice.UserInfoServiceApi;
import com.itheima.exception.CommonException;
import com.itheima.pojo.BlackList;
import com.itheima.pojo.UserInfo;
import com.itheima.vo.RecommendFriend;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class BlackListService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private BlackListServiceApi blackListServiceApi;
    @DubboReference
    private UserInfoServiceApi userInfoServiceApi;
    /**
     * 获取黑名单
     * @param page
     * @param pagesize
     * @return
     */
    public ResponseEntity getBlackList(Integer page, Integer pagesize) {
        //1.获取id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
//        //2.判断id是否失效
//        if (ObjectUtil.isNull(uid)){
//            throw new CommonException("token已失效");
//        }
        //3.调用api获取黑名单
        IPage<BlackList> blackListById = blackListServiceApi.getBlackListById(uid, page, pagesize);
        //4.创建黑名单详细信息集合
        ArrayList<UserInfo> blackUserInfoList = new ArrayList<>();
        //5.获取黑名单的id
        for (BlackList blacklist : blackListById.getRecords()) {
            //通过黑名单id获取用户详细信息
            UserInfo blackUserInfo = userInfoServiceApi.getUserInfoById(blacklist.getBlackUserId());
            //将数据封装至集合
            blackUserInfoList.add(blackUserInfo);
        }
        //6.创建返回值
        RecommendFriend<UserInfo> result = new RecommendFriend<>();
        //7.封装返回值
        result.setPagesize(pagesize);
        result.setPage(page);
        result.setItems(blackUserInfoList);
        //8.返回结果
        return ResponseEntity.ok(result);
    }

    /**
     * 移除黑名单
     * @param blackUserId
     * @return
     */
    public ResponseEntity removeBlackList(Long blackUserId) {
        //1.调用blacklistapi删除黑名单
        blackListServiceApi.removeBlackList(blackUserId);
        //2.返回
        return ResponseEntity.ok("删除成功");
    }
}
